#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mycap.h"
#include "logger.h"
#include "helpers.h"
#include "init.h"
#include "headerhandler.h"

CAP_RETURN MyCAP::ConnectCAP(void** param1, HeaderHandlerInterface* hhi){
	char* host;

	if(!*param1)
		*param1 = (MyCapConnection*)malloc(sizeof(MyCapConnection));
	host = (char*)hhi->GetHeader("Host"); 

	((MyCapConnection*)*param1)->requeston=0;

	if(host){
		logd <<"CAP: connect "<< host<<" "<< hhi->GetRequestLine()<<lend;	
	}
	else{
		logd <<"CAP: connect null "<< hhi->GetRequestLine()<<lend;	
		hhi->DisplayHeaders();
	}

	return CAP_NOCHANGE;
}

void MyCAP::CloseCAP(void** param1){
	if(*param1){
		free(*param1);
		*param1=0;
	}
}


CAP_RETURN MyCAP::RequestCAP(void** param1, char** inout, unsigned int* inoutsize, HeaderHandlerInterface* hhi){
	//return CAP_NOCHANGE;
	logd<<"CAP: request " << hhi->GetRequestLine()<< " "<<hhi->GetHeader("Host")<<lend;
	if(!*param1){
		logd<<"CAP: request null param1 "<<hhi->GetRequestLine()<<lend;
	}
	else{
		((MyCapConnection*)*param1)->requeston=1;
		snprintf(((MyCapConnection*)*param1)->request.val1, MYCAP_STRING_LEN, "%s-%s", hhi->GetRequestLine(), hhi->GetHeader("Host"));
	}
	return CAP_NOCHANGE;
}


CAP_RETURN MyCAP::ResultCAP(void** param1, char** inout, unsigned int* inoutsize, HeaderHandlerInterface* hhi){
	//return CAP_NOCHANGE;
	if(*param1){
		/*
		if(strstr(hhi->GetHeader("content-type"),"text/html")){
			printchararray(*inout, *inoutsize, "BUFFFEEERRRR");
		}
		*/
		if(((MyCapConnection*)*param1)->requeston==1){
			logd<<"CAP: Response "<<((MyCapConnection*)*param1)->request.val1 << " " << hhi->GetRequestLine() << " " <<lend;
		}
		else{
			logd << "CAP: Response null param:request" <<  hhi->GetRequestLine() <<" "<< *inoutsize <<lend;
		}
		
		//free((MyCapConnection*)*param1);
	}
	else{
		logd << "CAP: Response null param" <<  hhi->GetRequestLine() <<" "<< *inoutsize <<lend;
	}
	return CAP_NOCHANGE;
}


CAP_RETURN MyCAP::InitCAP(){
	InitParameters* sections, * initp;
	char tmps8[8];
	int i;
	char* c;

	initp = new InitParameters();
	if(initp->ReadInitFile("mycap.ini")==-1){
		loge<<"MYCAP: Could not load default preproxy.ini file"<<lend;
	}

	whitesites.count=0;
	if(sections=initp->GetSectionByName("White-Domains")){
		for(i=0; (sprintf(tmps8,"%d",i))&&(c = (char*)sections->GetInitParameter(tmps8)) ; i++){
			whitesites.entries = (char**)realloc(whitesites.entries, sizeof(char*)*(i+1));
			whitesites.entries[i] = (char*)calloc(strlen(c)+1, 1);
			memcpy(whitesites.entries[i], c, strlen(c));
			printf("hello %s\n", c);
		}
	}

	blacksites.count=0;
	if(sections=initp->GetSectionByName("Black-Domains")){



	}

	return CAP_NOCHANGE;
}


CAP_RETURN MyCAP::ClearCAP(){
	return CAP_NOCHANGE;
}




